package com.liao.myblog.controller.admin;

import com.liao.myblog.enums.ResultCode;
import com.liao.myblog.service.BlogService;
import com.liao.myblog.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@RequestMapping(value = "/upload")
@Controller
public class UploadController {
    @Autowired
    private BlogService blogService;

    @ResponseBody
    @PostMapping(value = "/blogImg")
    public ResultVO<Object> uploadImg(@RequestParam(value = "file") MultipartFile multipartFile) {
        if (multipartFile.getSize() > 1024 * 1024 * 5) {
            return new ResultVO<>(ResultCode.FILE_SIZE_ERROR, "上传的最大文件为5M");
        }
        String filename = multipartFile.getOriginalFilename();
        if (filename == null) {
            return new ResultVO<>(ResultCode.ERROR);
        }
//        System.out.println("filename:" + filename);
        //获取文件后缀名
//        String path = "http://localhost:8080/blog/amaze/blogImg/";

        String substring = filename.substring(filename.lastIndexOf("."));
//        System.out.println("文件后缀:" + substring);
        URL resource = this.getClass().getClassLoader().getResource("static");

        if (resource == null) {
            return new ResultVO<>(ResultCode.ERROR);
        }

        String path = resource.getPath();
        filename = path + "/blog/amaze/blogImg/";
        File fileDirectory = new File(filename);

        String imgName = UUID.randomUUID() + substring;

        String newFileName = filename + imgName;
        File destFile = new File(newFileName);
        try {
            if (!fileDirectory.exists()) {
                fileDirectory.mkdir();
            }
            multipartFile.transferTo(destFile);
            return new ResultVO<>(ResultCode.SUCCESS, "/blog/amaze/blogImg/" + imgName);
        } catch (IOException e) {
            return new ResultVO<>(ResultCode.ERROR);
        }
    }
}
